package com.crl.module.avatar.core
{
	import com.crl.manager.ITickable;
	import com.crl.module.avatar.action.IAction;
	
	
	public class ActionExecuter implements ITickable
	{
		private var actor:IActor;
		private var actions:Array;
		public function ActionExecuter(actor:IActor)
		{
			this.actor=actor;
			actions=[];
		}
		
		
		public function clear(fireError:Boolean=false):void{
			var action:IAction;
			var len:int=actions.length;
			
			var i:int=0;
			
			var tempActions:Array=[];
			
			while(i<len){
				action=actions[i];
				
				if(action.giveup()){
					tempActions.push(action);
				}else{
					if(fireError)throw new Error("不能停止动作"+action);
				}
				
			}
			
			actions=tempActions;
		}
		
		/**
		 * 做一个动作; 
		 * @param action
		 * 
		 */		
		public function execute(action:IAction):void{
			var tempAction:IAction=getBlock(action);
			
			if(tempAction){
				throw new Error(tempAction.blockMessage);
			}
			
			this.tryReplace(action);
			
			action.execute(actor);
			if(action.isFinished==false){
				actions.push(action);
			}
		}
		
		public function tick(time:int):void
		{
			var action:IAction;
			var len:int=actions.length;
			
			var i:int=0;
			while(i<len){
				action=actions[i];
				
				if(action.isFinished){
					actions.splice(i,1);
					i--;
					len--;
				}else{
					action.onTick(actor);
				}
				i++;
			}
		}
		
		
		protected function tryReplace(value:IAction) : void{
			var action:IAction;
			var len:int=actions.length;
			
			var i:int=0;
			while(i<len){
				action=actions[i];
				if (action.replace(value)){
					actions.splice(i,1);
					i--;
					len--;
				}
				i++;
			}
		}
		
		/**
		 * 取得限制当前action 的action; 
		 * @param action 是否被限制action;
		 * @return 限制action;
		 * 
		 */		
		public function getBlock(value:IAction):IAction{
			var action:IAction;
			var len:int=actions.length;
			
			var i:int=0;
			while(i<len){
				action=actions[i];
				if(action.isFinished==false && action.isBlock(value))return action;
				i++;
			}
			return null;
		}
	}
}